﻿@using EmployeeLeaveSystem.Client.Components;
@using EmployeeLeaveSystem.Client.Components;
@using EmployeeLeaveSystem.Shared.Models;
@using EmployeeLeaveSystem.Shared;
@inject IMessageService _MessageService;
@inject HttpClient _HttpClient;
@inject ModalService _modalService;

<Select @bind-DataSource="departments"
        TItem="Department"
        TItemValue="int?"
        @bind-Value="DepartmentId"
        LabelName="@nameof(Department.Name)"
        ValueName="@nameof(Department.Id)"
        Placeholder="选择一个部门"
        Loading="@_SelectLoading"
        OnFocus="@SelectFocus"
        OnSelectedItemChanged="e=>OnSelectedFinished(e.Id)">
</Select>
<h5>规则制定记录表：</h5>
<p>以最后一次的发布记录为准，您可以修改本部门的薪水规则制定细节</p>
<Table DataSource="listRules" TableLayout="fixed" RowClassName="@(_=>"editable-row")" Bordered ScrollX="auto" Style="min-width:100%">
    <ChildContent Context="context">
        <Column TData="string" Title="Id">
            @context.Id
        </Column>
        <Column TData="string" Title="规则开始时间">
            @if (!editCache[context.Id].edit) {
                @context.StartTime
            } else {
                <DatePicker TValue="DateTime" ShowTime="@true" @bind-Value="editCache[context.Id].data.StartTime" />
            }
        </Column>
        <Column TData="string" Title="规则结束时间">
            @if (!editCache[context.Id].edit) {
                @context.EndTime
            } else {
                <DatePicker TValue="DateTime" ShowTime="@true" @bind-Value="editCache[context.Id].data.EndTime" />
            }
        </Column>
        <Column TData="string" Title="基础薪水">
            @if (!editCache[context.Id].edit) {
                @context.BaseSalary
            } else {
                <Input @bind-Value="editCache[context.Id].data.BaseSalary" />
            }
        </Column>
        <Column TData="string" Title="加班奖励薪水（CNY/H）">
            @if (!editCache[context.Id].edit) {
                @context.AddSalaryOverTime
            } else {
                <Input @bind-Value="editCache[context.Id].data.AddSalaryOverTime" />
            }
        </Column>
        <Column TData="string" Title="扣除薪水（CNY/H）">
            @if (!editCache[context.Id].edit) {
                @context.CutSalaryComeLate
            } else {
                <Input @bind-Value="editCache[context.Id].data.CutSalaryComeLate" />
            }
        </Column>
        <ActionColumn Title="Action">
            @if (!editCache[context.Id].edit) {
                <a @onclick="() => startEdit(context.Id)">Edit</a>
                <Popconfirm Title="Sure to Delete?"
                        OnConfirm="() => Delete(context.Id)"
                        OkText="Yes"
                        CancelText="No">
                    <a>Delete</a>
                </Popconfirm>
            } else {
                <a @onclick="() => saveEdit(context.Id)" class="save">Save</a>
                <Popconfirm Title="Sure to cancel?"
                        OnConfirm="() => cancelEdit(context.Id)"
                        OkText="Yes"
                        CancelText="No">
                    <a>Cancel</a>
                </Popconfirm>
            }
        </ActionColumn>
    </ChildContent>
</Table>

<SalaryRules Id="DepartmentId" />
<h5>为此部门新增一条规则：</h5>
<Form Model="nowRules" OnFinish="AddRules">
    <FormItem Label="标题">
        <Input @bind-Value="nowRules.Name" />
    </FormItem>
    <FormItem Label="开始时间">
        <DatePicker TValue="DateTime" ShowTime="@true" @bind-Value="nowRules.StartTime" />
    </FormItem>
    <FormItem Label="结束时间">
        <DatePicker TValue="DateTime" ShowTime="@true" @bind-Value="nowRules.EndTime" />
    </FormItem>
    <FormItem Label="基础薪水">
        <Input @bind-Value="nowRules.BaseSalary" />
    </FormItem>
    <FormItem Label="加班奖励薪水（CNY/H）">
        <Input @bind-Value="nowRules.AddSalaryOverTime" />
    </FormItem>
    <FormItem Label="每次迟到扣除薪水（CNY）">
        <Input @bind-Value="nowRules.CutSalaryComeLate" />
    </FormItem>
    <Button HtmlType="submit">新增</Button>
</Form>

@code {
    NowRules nowRules = new();
    List<NowRules> listRules = new();
    List<Department> departments = new();
    IDictionary<int, (bool edit, NowRules data)> editCache = new Dictionary<int, (bool edit, NowRules data)>();
    int? DepartmentId = 0;
    async void OnSelectedFinished(int value) {
        if (value == 0) return;
        listRules = await _HttpClient.GetFromJsonAsync<List<NowRules>>($"api/Salary/GetAllInfosByDepartmentId?id={value}");
        foreach (var item in listRules) {
            editCache[item.Id] = (false, item);
        }
        InvokeAsync(StateHasChanged);
    }
    // 表格编辑
    void startEdit(int id) {
        var data = editCache[id];
        editCache[id] = (true, data.data); // add a copy in cache
    }

    void cancelEdit(int id) {
        var data = listRules.FirstOrDefault(item => item.Id == id);
        editCache[id] = (false, data); // recovery
    }

    async void saveEdit(int id) {
        var index = listRules.FindIndex(item => item.Id == id);
        listRules[index] = editCache[id].data; // apply the copy to data source
        editCache[id] = (false, listRules[index]); // don't affect rows in editing

        // 上传到服务器
        await _HttpClient.PostAsJsonAsync("api/Salary/UpdateRules", listRules[index]);
        await _MessageService.Success("更新成功");
    }

    async void Delete(int id) {
        try {
            var res = await _HttpClient.GetAsync($"api/Salary/DeleteRules?id={id}");
            if (res.StatusCode == System.Net.HttpStatusCode.OK) {
                listRules.Remove(editCache[id].data);
                editCache.Remove(id);
                InvokeAsync(StateHasChanged);
                await _MessageService.Success("删除成功");
            } else {
                await _MessageService.Error("失败！因为现在删除的，拥有一些关联关系，再未能清除之前，无法删除");
            }
        }
        catch (Exception ex) {
            await _MessageService.Error("失败！" + ex.Message);
        }
    }

    async void AddRules() {
        nowRules.StaffId = GobalManager.myInfo.Id;
        nowRules.DepartmentId = (int)DepartmentId;
        await _HttpClient.PostAsJsonAsync("api/Salary/AddRules", nowRules);
        _MessageService.Success("添加规则成功");
        OnSelectedFinished((int)DepartmentId);
    }

    // !====部门选择=====
    bool _SelectLoading = false;
    async void SelectFocus() {
        _SelectLoading = true;
        _MessageService.Info("加载部门中");
        departments = await _HttpClient.GetFromJsonAsync<List<Department>>("api/Department/GetAllDepartmentInfos");
        _MessageService.Success("加载完成");
        _SelectLoading = false;
        InvokeAsync(StateHasChanged);
    }
}
